<template>
  <div class="afterSaleRecord">
    <ContentWrap>
      <FormContainer :column="4">
        <el-form ref="form" :model="formData" :rules="formRules" label-width="95px">
          <el-form-item prop="officeCode" label="办事处">
            <SearchSelectPicker
              url="/call-center/api/v1/mscInfo/office/ref/page"
              placeholder="请选择"
              lable-name="name"
              value-name="code"
              method="get"
              :value.sync="formData.officeCode"
              :lable.sync="formData.officeName"
              @selectChange="officeSelectChange"
            ></SearchSelectPicker>
          </el-form-item>
          <el-form-item prop="disCode" label="经销商">
            <SearchSelectPicker
              url="/call-center/api/v1/mscInfo/dealer/ref/page"
              method="get"
              placeholder="请选择经销商"
              :params="{query:{officeCode:formData.officeCode},type:0}"
              lable-name="name"
              value-name="code"
              custom-name="codeOrName"
              :parent-id="formData.officeCode"
              :current-id.sync="formData.disId"
              :value.sync="formData.disCode"
              :lable.sync="formData.disName"
              clearable
            ></SearchSelectPicker>
          </el-form-item>
          <el-form-item prop="shopCode" label="门店">
            <SearchSelectPicker
              url="/call-center/api/v1/mscInfo/shop/page"
              placeholder="请选择"
              lable-name="shopName"
              value-name="shopCode"
              custom-name="shopName"
              :params="{query:{shopCode: formData.shopCode, customerName: formData.disName}, type:1}"
              :value.sync="formData.shopCode"
              :lable.sync="formData.shopName"
            ></SearchSelectPicker>
          </el-form-item>
          <el-form-item prop="afterSaleCall" label="售后电话" hidden>
            <el-input v-model.trim="formData.afterSaleCall" placeholder="请输入售后电话" clearable />
          </el-form-item>
          <el-form-item prop="afterSaleContact" label="售后联系人">
            <el-input v-model.trim="formData.afterSaleContact" placeholder="请输入售后联系人" clearable />
          </el-form-item>
          <el-form-item prop="contactPhone" label="售后联系人电话">
            <el-input v-model.trim="formData.contactPhone" placeholder="请输入售后联系人电话" clearable />
          </el-form-item>
          <el-form-item prop="ecContact" label="电商联系人">
            <el-input v-model.trim="formData.ecContact" placeholder="请输入电商联系人" clearable />
          </el-form-item>
          <el-form-item prop="ecContactPhone" label="电商联系人电话">
            <el-input v-model.trim="formData.ecContactPhone" placeholder="请输入电商联系人电话" clearable />
          </el-form-item>
          <el-form-item show more>
            <Button @click="resetHandle('form')">重置</Button>
            <Button type="primary" enter :loading="isLoading" @click="queryHandle">查询</Button>
          </el-form-item>
        </el-form>
      </FormContainer>
      <div class="table-list-box">
        <el-table
          ref="shopAfterTable"
          v-loading="isLoading"
          border
          height="330"
          highlight-current-row
          header-row-class-name="table-list-header"
          tooltip-effect="dark"
          style="width: 100%"
          :data="dataList"
        >
          <el-table-column type="index" :index="indexMethod" label="序号" width="50" align="center" />
          <el-table-column prop="officeName" label="办事处" align="left" width="160" :show-overflow-tooltip="true" />
          <el-table-column prop="disName" label="经销商" align="left" width="249" :show-overflow-tooltip="true" />
          <el-table-column prop="shopName" label="门店" align="left" width="249" :show-overflow-tooltip="true" />
          <el-table-column prop="afterSaleCall" label="售后电话" width="120">
            <template slot-scope="scope">
              <el-input v-model.trim="scope.row.afterSaleCall" :disabled="isEditObj[scope.$index].a"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="afterSaleContact" label="售后联系人" width="120">
            <template slot-scope="scope">
              <el-input v-model.trim="scope.row.afterSaleContact" :disabled="isEditObj[scope.$index].a"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="contactAccount" label="售后联系人QUP用户名" width="120">
            <!-- <template slot-scope="scope">
              <el-input v-model.trim="scope.row.contactAccount" :disabled="isEditObj[scope.$index].a"></el-input>
            </template> -->
          </el-table-column>
          <el-table-column prop="contactPhone" label="售后联系人电话" width="130">
            <template slot-scope="scope">
              <el-input v-model.trim="scope.row.contactPhone" :disabled="isEditObj[scope.$index].a"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="ecContact" label="电商业务联系人" width="130">
            <template slot-scope="scope">
              <el-input v-model.trim="scope.row.ecContact" :disabled="isEditObj[scope.$index].a"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="ecContactAccount" label="电商业务联系人QUP用户名" width="130">
            <!-- <template slot-scope="scope">
              <el-input v-model.trim="scope.row.ecContactAccount" :disabled="isEditObj[scope.$index].a"></el-input>
            </template> -->
          </el-table-column>
          <el-table-column prop="ecContactPhone" label="电商业务联系人电话" width="150">
            <template slot-scope="scope">
              <el-input v-model.trim="scope.row.ecContactPhone" :disabled="isEditObj[scope.$index].a"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="endProductCustomer" label="成品客户经理" width="130" :show-overflow-tooltip="true">
            <!-- <template slot-scope="scope">
              <el-input v-model.trim="scope.row.endProductCustomer" :disabled="isEditObj[scope.$index].a"></el-input>
            </template> -->
          </el-table-column>
          <el-table-column prop="endProductCustomerAccount" label="成品客户经理QUP用户名" width="130" :show-overflow-tooltip="true">
            <!-- <template slot-scope="scope">
              <el-input v-model.trim="scope.row.endProductCustomerAccount" :disabled="isEditObj[scope.$index].a"></el-input>
            </template> -->
          </el-table-column>
          <el-table-column prop="endProductCustomerPhone" label="成品客户经理电话" width="150" :show-overflow-tooltip="true">
            <!-- <template slot-scope="scope">
              <el-input v-model.trim="scope.row.endProductCustomerPhone" :disabled="isEditObj[scope.$index].a"></el-input>
            </template> -->
          </el-table-column>
          <el-table-column prop="signProductCustomer" label="定制客户经理" width="130" :show-overflow-tooltip="true">
            <!-- <template slot-scope="scope">
              <el-input v-model.trim="scope.row.signProductCustomer" :disabled="isEditObj[scope.$index].a"></el-input>
            </template> -->
          </el-table-column>
          <el-table-column prop="signProductCustomerAccount" label="定制客户经理QUP用户名" width="130" :show-overflow-tooltip="true">
            <!-- <template slot-scope="scope">
              <el-input v-model.trim="scope.row.signProductCustomerAccount" :disabled="isEditObj[scope.$index].a"></el-input>
            </template> -->
          </el-table-column>
          <el-table-column prop="signProductCustomerPhone" label="定制客户经理电话" width="150" :show-overflow-tooltip="true">
            <!-- <template slot-scope="scope">
              <el-input v-model.trim="scope.row.signProductCustomerPhone" :disabled="isEditObj[scope.$index].a"></el-input>
            </template> -->
          </el-table-column>
          <el-table-column prop="officeEbName" label="办事处商务姓名" width="130">
            <template slot-scope="scope">
              <el-input v-model.trim="scope.row.officeEbName" :disabled="isEditObj[scope.$index].a"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="officeEbAccount" label="办事处商务QUP账号" width="130">
            <!-- <template slot-scope="scope">
              <el-input v-model.trim="scope.row.officeEbAccount" :disabled="isEditObj[scope.$index].a"></el-input>
            </template> -->
          </el-table-column>
          <el-table-column prop="officeEbPhone" label="办事处商务电话" width="150">
            <template slot-scope="scope">
              <el-input v-model.trim="scope.row.officeEbPhone" :disabled="isEditObj[scope.$index].a"></el-input>
            </template>
          </el-table-column>

          <el-table-column prop="regionalName" label="区域专员" width="130">
            <template slot-scope="scope">
              <el-input v-model.trim="scope.row.regionalName" :disabled="isEditObj[scope.$index].a"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="regionalAccount" label="区域专员QUP账号" width="130">
            <!-- <template slot-scope="scope">
              <el-input v-model.trim="scope.row.regionalAccount" :disabled="isEditObj[scope.$index].a"></el-input>
            </template> -->
          </el-table-column>
          <el-table-column prop="regionalPhone" label="区域专员电话" width="150">
            <template slot-scope="scope">
              <el-input v-model.trim="scope.row.regionalPhone" :disabled="isEditObj[scope.$index].a"></el-input>
            </template>
          </el-table-column>

          <el-table-column label="操作" align="center" width="160" fixed="right">
            <template slot-scope="scope">
              <div v-show="isEditObj[scope.$index].a">
                <ShopAfterDetail :detail-info="scope.row"></ShopAfterDetail>
                <Button size="mini" type="primary" @click="editRecordHandle(scope.$index, scope.row)">编辑</Button>
              </div>
              <div v-show="!isEditObj[scope.$index].a" class="save-cancel-button">
                <Button size="mini" type="primary" @click="saveRecordHandle(scope.$index, scope.row)">保存</Button>
                <Button size="mini" @click="cancelRecordHandle(scope.$index, scope.row)">取消</Button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <CustomPagination
        :total="pageInfo.total"
        :page="pageInfo.page"
        :limit="pageInfo.rows"
        @pagination="paginationChange"
        @on-total="onlyCountFlag"
      ></CustomPagination>
    </ContentWrap>
  </div>
</template>
<script>
import ContentWrap from '@/components/ContentWrap'
import FormContainer from '@/components/FormContainer'
import Button from '@/components/Button'
import SearchSelectPicker from '@/components/SearchSelectPicker'
import CustomPagination from '@/components/CustomPagination'
import ShopAfterDetail from './details'
import { getShopAfterInfo, updeteShopAfter } from '@/api/shopAfter'
import { ArrayFormat } from '@/utils/params-format'
import { getOfficeDetail } from '@/api/mscInfo'
export default {
  name: 'AfterSaleRecord',
  components: {
    ContentWrap,
    FormContainer,
    Button,
    SearchSelectPicker,
    ShopAfterDetail,
    CustomPagination
  },
  data() {
    return {
      isLoading: false,
      total: false,
      formData: {
        officeCode: '',
        disCode: '',
        shopCode: '',
        afterSaleCall: '',
        afterSaleContact: '',
        contactPhone: '',
        ecContact: '',
        ecContactPhone: ''
      },
      pageInfo: {
        page: 1,
        rows: 10,
        total: 0
      },
      officeOption: [],
      disOption: [],
      shopOption: [],
      formRules: {
      },
      dataList: [],
      isEditObj: [],
      storeData: {}
    }
  },
  watch: {
    // 'formData.disCode': {
    //   handler(newVal, oldVal) {
    //     if (newVal !== oldVal && newVal) {
    //       if (!this.formData.officeCode) {
    //         this.findOfficeInfo(newVal)
    //       }
    //     }
    //   },
    //   immediate: true
    // }
  },
  mounted() {
  },
  methods: {
    // 获取经销商对应的办事处
    findOfficeInfo(disCode) {
      getOfficeDetail(disCode, { hiddenError: true }).then(res => {
        if (res.success === 1) {
          this.formData.officeName = res.data.name
          this.formData.officeCode = res.data.code
        }
      })
    },
    // 搜索
    queryHandle() {
      this.$refs.form.validate().then(() => {
        // FIXME:
        this.total = false
        this.pageInfo.page = 1
        this.pageInfo.total = 0
        this.getRecordList(false)
      })
    },
    // 获取列表信息
    getRecordList(onlyCountFlag) {
      if (!onlyCountFlag) {
        this.storeData = {}
        this.isEditObj = []
      }
      const params = new FormData()
      const coParams = { ...this.formData }
      delete coParams.disId
      const paramsArr = ArrayFormat(coParams)
      params.append('page', this.pageInfo.page)
      params.append('rows', this.pageInfo.rows)
      params.append('onlyCountFlag', onlyCountFlag)
      if (Array.isArray(paramsArr) && paramsArr.length) params.append('filtersRaw', JSON.stringify(paramsArr))
      this.isLoading = true
      getShopAfterInfo(params).then(res => {
        if (res.success === 1) {
          if (!this.total) {
            this.pageInfo.total = res.data.total
          }
          if (!onlyCountFlag) {
            const list = res.data.records
            this.dataList = list || []
            for (let i = 0; i < list.length; i++) {
              this.isEditObj.push({ a: true, alias: `edit${i}` })
            }
          } else {
            this.total = true
            this.pageInfo.total = res.data.total
          }
          this.$nextTick(() => {
            this.isLoading = false
          })
        }
      }, () => { this.isLoading = false })
    },
    /**
     * 选择每页多少条
     */
    handleSizeChange(pageSize) {
      this.$set(this.pageInfo, 'page', 1)
      this.$set(this.pageInfo, 'rows', pageSize)
      this.$nextTick(() => {
        this.getRecordList(false)
      })
    },
    /**
     * 分页
     */
    handleCurrentChange(currrentPage) {
      this.$set(this.pageInfo, 'page', currrentPage)
      this.$nextTick(() => {
        this.getRecordList(false)
      })
    },
    // 分页返回相应请求参数
    paginationChange(paramsObj) {
      this.$set(this.pageInfo, 'rows', paramsObj.rows)
      this.$set(this.pageInfo, 'page', paramsObj.page)
      this.$nextTick(() => {
        this.getRecordList(false)
      })
    },
    onlyCountFlag(paramsObj) {
      this.$set(this.pageInfo, 'rows', paramsObj.rows)
      this.$set(this.pageInfo, 'page', paramsObj.page)
      this.$nextTick(() => {
        this.getRecordList(true)
      })
    },
    // 序号
    indexMethod(index) {
      return index + 1
    },
    // 查看详情
    recordDetail() {},
    // 编辑
    editRecordHandle(index, row) {
      // 有且仅有一个编辑行
      this.isEditObj.forEach((item, index) => {
        if (!item.a) {
          this.cancelRecordHandle(index, item)
        }
      })
      this.storeData = { ...row }
      this.isEditObj[index].a = false
    },
    // 保存
    saveRecordHandle(index, row) {
      const parmas = { id: '', afterSaleCall: '', afterSaleContact: '', contactPhone: '', ecContact: '', ecContactPhone: '',
        contactAccount: '',
        ecContactAccount: '',
        endProductCustomer: '',
        endProductCustomerAccount: '',
        endProductCustomerPhone: '',
        signProductCustomer: '',
        signProductCustomerAccount: '',
        signProductCustomerPhone: '',
        officeEbName: '',
        officeEbAccount: '',
        officeEbPhone: '',
        regionalName: '',
        regionalAccount: '',
        regionalPhone: ''
      }
      Object.keys(parmas).forEach(key => {
        if (row[key]) parmas[key] = row[key]
      })
      // const phone = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/  座机+手机
      const phone = /^1\d{10}$/
      // 售后电话
      if (parmas.afterSaleCall !== '' && !/^\d*$/.test(parmas.afterSaleCall)) {
        this.$message({
          message: '请输入正确的售后号码',
          type: 'warning'
        })
        return
      }
      // 手机可以为空 FIX : 21437   门店售后档案管理内维护三方物流信息优化
      const validateKey = ['contactPhone', 'endProductCustomerPhone', 'signProductCustomerPhone', 'officeEbPhone', 'regionalPhone']
      for (const k of validateKey) {
        const v = parmas[k]
        if (v && v.length !== 11 && !phone.test(v)) {
          this.$message({
            message: '联系人电话格式错误或为空',
            type: 'warning'
          })
          return
        }
      }
      this.$msgbox({
        title: '修改',
        showCancelButton: true,
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        message: '确定要修改该档案？',
        type: 'warning'
      }).then(() => {
        updeteShopAfter(parmas).then(res => {
          if (res.success === 1) {
            this.storeData = {}
            this.isEditObj[index].a = true
            this.$message({
              message: '修改成功',
              type: 'success'
            })
          }
        }, () => {
          this.$set(this.dataList, index, row)
        })
      })
    },
    // 取消
    cancelRecordHandle(index, row) {
      row = { ...this.storeData }
      this.$set(this.dataList, index, row) // 取消修改时恢复原来数据
      this.isEditObj[index].a = true
    },
    // 重置表单
    resetHandle(formName) {
      Object.keys(this.formData).forEach(key => {
        this.$set(this.formData, key, '')
      })
      this.storeData = {}
      this.$refs[formName].resetFields()
    },
    officeSelectChange(data) {
      this.$set(this.formData, 'disCode', '')
      this.$set(this.formData, 'disName', '')
    }
  }
}
</script>
<style lang='scss' scoped>
.afterSaleRecord /deep/ .el-input.is-disabled .el-input__inner {
  background: transparent;
  border: none;
  color: #333;
  cursor: text;
}
.afterSaleRecord /deep/ .save-cancel-button button:last-child {
  margin-left: 0;
}
</style>
